<template>
  <div>
    <van-search
      v-model="searchTxt"
      show-action
      label="商品"
      placeholder="请输入搜索关键词"
      background="#f66"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="content">
      <h3>历史搜索</h3>
      <div class="searchHis">
        <div class="search" v-for="his in histories" :key="his">
          {{his}}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//  histories
export default {
  data () {
    return {
      searchTxt: '',
      histories: localStorage.getItem('his') ? JSON.parse(localStorage.getItem('his')) : []
    }
  },
  methods: {
    onSearch () {
      // 存 历史记录
      // 先取  转换成数组  往数组中添加一个 然后 再 转化成字符串 存回去
      let his = localStorage.getItem('his') ? JSON.parse(localStorage.getItem('his')) : []
      his.unshift(this.searchTxt)
      // 去重之后 再 存
      his = [...new Set(his)]
      if (his.length >= 2) {
        his.length = 2
      }
      localStorage.setItem('his', JSON.stringify(his))
      this.$router.push({
        path: '/searchResult',
        query: {
          word: this.searchTxt
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.searchHis{
  display:flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  .search{
    line-height:40px;
    font-size:14px;
    color:#333;
    padding:0 10px;
    margin-left:10px;
    margin-top:10px;
    background-color: #f1f1f1;
  }
}
</style>
